#!/bin/bash

# 脚本版本
SCRIPT_VERSION="1.0.0"

# 函数：显示帮助信息
show_help() {
	cat <<EOF
用法:
    $(basename "$0") [命令] [选项]

命令:
    install [-y]
        安装电池监控服务。如果加上 -y 选项，则使用默认设置自动安装。
    uninstall
        卸载电池监控服务。

选项:
    -h, --help
        显示此帮助信息。
    -v, --version
        显示脚本版本。

示例:
    $(basename "$0") install
        启动交互式安装流程。
    $(basename "$0") install -y
        使用默认设置自动安装。
    $(basename "$0") uninstall
        卸载电池监控服务。
EOF
}

# 函数：显示脚本版本
show_version() {
	echo "$(basename "$0") 版本: $SCRIPT_VERSION"
}

# 函数：提示用户输入变量
prompt_variable() {
	local prompt=$1
	local default_value=$2
	local variable_name=$3

	read -p "$prompt (默认值: $default_value): " input
	if [[ -z "$input" ]]; then
		input=$default_value
	fi
	eval "$variable_name='$input'"
}

# 函数：检查文件夹存在性和写权限
check_directory() {
	local directory=$1
	if [[ ! -d "$directory" ]]; then
		echo "错误：目录 $directory 不存在。"
		exit 1
	fi

	if [[ ! -w "$directory" ]]; then
		echo "错误：没有写权限到目录 $directory。"
		exit 1
	fi
}

# 函数：检查 upower 是否已安装
check_upower_installed() {
	if ! command -v upower &>/dev/null; then
		echo "正在安装 upower..."
		sudo apt update && sudo apt install -y upower
	else
		echo "upower 已经安装。"
	fi
}

# 函数：创建电池监控脚本
create_battery_monitor_script() {
	local service_name=$1
	local low_battery_threshold=$2
	local webhook_url=$3
	local battery_device_path=$4
	sudo tee /usr/local/bin/${service_name}.sh >/dev/null <<EOF
#!/bin/bash

LOW_BATTERY_THRESHOLD=$low_battery_threshold
WEBHOOK_URL="$webhook_url"
BATTERY_DEVICE_PATH="$battery_device_path"

# 获取电池状态和电量
BATTERY_STATUS=\$(upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep state | awk '{print \$2}')
BATTERY_LEVEL=\$(upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep percentage | awk '{print \$2}' | sed 's/%//')

if [[ "\$BATTERY_STATUS" == "discharging" ]] && (( "\$BATTERY_LEVEL" <= "\$LOW_BATTERY_THRESHOLD" )); then
    curl -s -X POST "\$WEBHOOK_URL" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "电池电量低于 '\$LOW_BATTERY_THRESHOLD\%'，系统即将关机。当前电量：'\$BATTERY_LEVEL\%'。"}}'
    sudo shutdown now
else
    echo "Battery level is sufficient or charging: \$BATTERY_LEVEL%, status: \$BATTERY_STATUS"
fi
EOF
	sudo chmod +x /usr/local/bin/${service_name}.sh
}

# 函数：创建 systemd 服务文件
create_systemd_service_file() {
	local service_name=$1

	check_directory /etc/systemd/system

	sudo tee /etc/systemd/system/${service_name}.service >/dev/null <<EOF
[Unit]
Description=Battery Monitor Service

[Service]
Type=simple
ExecStart=/usr/local/bin/${service_name}.sh
EOF
}

# 函数：创建 systemd 定时器文件
create_systemd_timer_file() {
	local service_name=$1
	local on_boot_sec=$2
	local on_unit_active_sec=$3

	local timer_name="${service_name}.timer"

	check_directory /etc/systemd/system

	sudo tee /etc/systemd/system/${timer_name} >/dev/null <<EOF
[Unit]
Description=Run Battery Monitor Script Every 5 Minutes

[Timer]
OnUnitActiveSec=${on_unit_active_sec}
OnBootSec=${on_boot_sec}
Unit=${service_name}.service

[Install]
WantedBy=timers.target
EOF
}

# 函数：启用并启动定时器
enable_and_start_timer() {
	local timer_name=$1

	sudo systemctl daemon-reload
	sudo systemctl enable --now ${timer_name}
}

# 函数：检查定时器状态
check_timer_status() {
	local timer_name=$1

	systemctl list-timers --all | grep ${timer_name}
}

# 函数：安装
install() {
	local service_name
	local timer_name
	local low_battery_threshold
	local webhook_url
	local battery_device_path
	local on_boot_sec
	local on_unit_active_sec

	# 检查是否已安装
	if [[ -f /usr/local/bin/${service_name}.sh ]] || [[ -f /etc/systemd/system/${service_name}.service ]] || [[ -f /etc/systemd/system/${timer_name} ]]; then
		echo "错误：已检测到现有安装。请先卸载或选择其他服务名称。"
		exit 1
	fi

	# 获取用户输入或使用默认值
	if [[ "$1" != "-y" ]]; then
		prompt_variable "请输入电量阈值（例如：15）" 15 low_battery_threshold
		prompt_variable "请输入企业微信 Webhook URL" "" webhook_url
		prompt_variable "请输入电池设备路径（例如：/org/freedesktop/UPower/devices/battery_BAT1）" "/org/freedesktop/UPower/devices/battery_BAT1" battery_device_path
		prompt_variable "请输入服务名称（例如：battery-monitor）" "battery-monitor" service_name
		prompt_variable "请输入系统启动后首次运行的时间（例如：5min）" "5min" on_boot_sec
		prompt_variable "请输入每次运行的时间间隔（例如：5min）" "5min" on_unit_active_sec
	else
		low_battery_threshold=15
		webhook_url=""
		battery_device_path="/org/freedesktop/UPower/devices/battery_BAT1"
		service_name="battery-monitor"
		on_boot_sec="5min"
		on_unit_active_sec="5min"
	fi

	timer_name="${service_name}.timer"

	check_upower_installed
	create_battery_monitor_script "$service_name" "$low_battery_threshold" "$webhook_url" "$battery_device_path"
	create_systemd_service_file "$service_name"
	create_systemd_timer_file "$service_name" "$on_boot_sec" "$on_unit_active_sec"
	enable_and_start_timer "$timer_name"
	check_timer_status "$timer_name"

	echo "安装和配置完成。"
}

# 函数：卸载
uninstall() {
	local service_name=$1
	local timer_name="${service_name}.timer"

	# 检查是否存在
	if ! [[ -f /usr/local/bin/${service_name}.sh ]] && ! [[ -f /etc/systemd/system/${service_name}.service ]] && ! [[ -f /etc/systemd/system/${timer_name} ]]; then
		echo "错误：未检测到现有安装。"
		exit 1
	fi

	# 停用并禁用定时器
	echo "正在停用并禁用定时器..."
	sudo systemctl stop ${timer_name}
	sudo systemctl disable ${timer_name}

	# 删除文件
	echo "正在删除文件..."
	sudo rm -f /usr/local/bin/${service_name}.sh
	sudo rm -f /etc/systemd/system/${service_name}.service
	sudo rm -f /etc/systemd/system/${timer_name}

	# 重新加载 systemd 配置
	sudo systemctl daemon-reload

	echo "卸载完成。"
}

# 主程序
case "$1" in
install)
	if [[ "$2" == "-y" ]]; then
		install "-y"
	else
		install
	fi
	;;
uninstall)
	prompt_variable "请输入服务名称（例如：battery-monitor）" "battery-monitor" service_name
	uninstall "$service_name"
	;;
-h | --help)
	show_help
	;;
-v | --version)
	show_version
	;;
*)
	if [[ -z "$1" ]]; then
		show_help
	else
		echo "未知命令: $1"
		show_help
	fi
	;;
esac
